package com.yulinlin.authorization.service;



import cn.hutool.core.codec.Base64;
import com.yulinlin.authorization.modules.AuthService;
import com.yulinlin.authorization.modules.admin.service.AdminAuthService;
import com.yulinlin.authorization.util.OauthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {






    @Autowired
    private Map<String,AuthService> authServiceMap;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
       HttpServletRequest request =  requestAttributes.getRequest();



        String loginType = request.getParameter("login_type");
        String grantType =  request.getParameter("grant_type");


        AuthService authService =  authServiceMap.get(loginType);
        if(authService != null){
            switch (grantType){
                case "password":{
                    return authService.loadUserByUsername(username);


                }case "refresh_token":{
                    return authService.loadUserById(username);

                }default:{
                    throw new AuthenticationServiceException("暂不支持的登录方式" + loginType);
                }
            }

        }else{
            throw new AuthenticationServiceException("暂不支持的登录方式" + loginType);

        }




    }
}
